package com.company.threads;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/* 线程打印奇偶数  2021/1/15 14:32 xiaohutu */
public class ThreadMain {
    public static void main(String[] args) throws InterruptedException {
        ThreadMain main = new ThreadMain(10, 0);
        Thread thread1 = new Thread(() -> {
            main.print();
        }, "thread1");
        Thread thread2 = new Thread(main::print, "thread2");
        thread1.start();
        thread2.start();


    }

    //方法一
    private final Object monitor = new Object();
    private final int limit;
    private volatile int count;

    public ThreadMain(int limit, int count) {
        this.limit = limit;
        this.count = count;
    }

    public void print() {
        synchronized (monitor) {
            while (count < limit) {
                try {
                    System.out.println(String.format("线程[%s]打印数字:%d", Thread.currentThread().getName(), ++count));
                    monitor.notifyAll();
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //方法二
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void print1() {
        lock.lock();
        try {
            while (count < limit) {
                System.out.println(String.format("线程[%s]打印数字:%d", Thread.currentThread().getName(), ++count));
                condition.signalAll();
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    //ignore
                }
            }
        } finally {
            lock.unlock();
        }
    }

}
